package com.wanlian.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wanlian.dao.UserAuthorityDao;
import com.wanlian.entity.UserAuthority;
import com.wanlian.model.PageResult;
import com.wanlian.vo.Page;
import org.springframework.stereotype.Component;


@Component
public class UserAuthorityDaoImpl extends GenericDaoImpl<UserAuthority> implements UserAuthorityDao
{

    public UserAuthorityDaoImpl()
    {
        super(UserAuthority.class);
    }

    @Override
    public void add(UserAuthority t)
    {
        super.add(t);
    }

    @Override
    public void delete(int id)
    {
        super.delete(id);
    }

    @Override
    public void doedit(UserAuthority userAuthority)
    {
        this.update(userAuthority);
    }

    @Override
    public UserAuthority getUserAuthority(int id)
    {
        return this.queryById(id);
    }

    @Override
    public List<UserAuthority> queryUserAuthority(int userid)
    {
        return queryForListByWhere(" isdel = 0 and isenable = 1 and userid = " + userid, null);
    }

    @Override
    public UserAuthority getIsExistUserAuthority(int userid, int authorityid)
    {
        String hql = "from " + this.entityClassName() + " where userid =" + userid + " and authorityid = " + authorityid;
        return this.queryForObject(hql, null);
    }

    @Override
    public PageResult queryPageList(UserAuthority userAuthority, Page page)
    {
        StringBuffer sqlWhere = new StringBuffer(" where isdel = 0");
        ArrayList<Object> params = new ArrayList<Object>();
        if (userAuthority.getUserid() != 0)
        {
            sqlWhere.append(" and userid = ?");
            params.add(userAuthority.getUserid());
        }
        if (userAuthority.getAuthorityid() != 0)
        {
            sqlWhere.append(" and authorityid = ?");
            params.add(userAuthority.getAuthorityid());
        }
        List<UserAuthority> models = this.queryForListByPage("from " + entityClassName() + sqlWhere + " order by lastupdatetime", params.toArray(), page);
        String hql = String.format("select count(*) from %s " + sqlWhere, entityClassName());
        Long totalSize = this.queryCount(hql, params.toArray());
        PageResult pageResult = new PageResult();
        pageResult.setTotalSize(totalSize);
        pageResult.setResultList(models);
        return pageResult;
    }

    @Override
    public List<UserAuthority> queryByAuthorityid(int authorityid)
    {
        return queryForListByWhere(" isdel = 0 and authorityid = " + authorityid, null);
    }

    @Override
    public void deleteByUserId(int userId)
    {
        String hql = String.format("delete from %s where userd=:userId", this.entityClassName());
        Map<String, Object> paramap = new HashMap<>();
        paramap.put("userId", userId);
        this.executeHql(hql, paramap);
    }
}
